/**
 * 
 */
package com.nextive.interview.service.impl;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.nextive.interview.dto.UserPreferences;
import com.nextive.interview.service.UserInfoService;

/**
 * @author Cesar Roman
 *
 */
public class UserInfoServiceImpl implements UserInfoService {

	private Context context;
	
	public UserInfoServiceImpl(Context context) {
		
		this.context = context;
		
	}
	
	@Override
	public boolean isUserFirstAccess() {
		
		SharedPreferences sharedPreferences = obtainSharedPreferences();
		return !sharedPreferences.contains(USER_INFO_KEYS.NAME.name());
		
	}

	// TODO - any validations on inputs ??
	@Override
	public void saveUserInfo(String name, String email, String recipient,
			METRICS metric) {
		
		SharedPreferences sharedPreferences = obtainSharedPreferences();
		Editor editor = sharedPreferences.edit();
		
		editor.putString(USER_INFO_KEYS.NAME.name(), name);
		editor.putString(USER_INFO_KEYS.EMAIL.name(), email);
		editor.putString(USER_INFO_KEYS.RECIPIENT.name(), recipient);
		editor.putString(USER_INFO_KEYS.OPTION.name(), metric.name());
		
		editor.commit();
		
	}
	
	@Override
	public UserPreferences fetchUserInfo() {
		
		SharedPreferences sharedPreferences = obtainSharedPreferences();
		
		return new UserPreferences(
				sharedPreferences.getString(USER_INFO_KEYS.NAME.name(), USER_INFO_KEYS.NAME.getDefaultValue()),
				sharedPreferences.getString(USER_INFO_KEYS.EMAIL.name(), USER_INFO_KEYS.EMAIL.getDefaultValue()),
				sharedPreferences.getString(USER_INFO_KEYS.RECIPIENT.name(), USER_INFO_KEYS.RECIPIENT.getDefaultValue()),
				buildMetric(sharedPreferences.getString(USER_INFO_KEYS.OPTION.name(), USER_INFO_KEYS.OPTION.getDefaultValue())));
		
	}
	
	private static METRICS buildMetric(String value) {
		
		try {
		
			return METRICS.valueOf(value);
			
		} catch(IllegalArgumentException e) {
			return METRICS.valueOf(USER_INFO_KEYS.OPTION.getDefaultValue());
		}
		
	}

	private SharedPreferences obtainSharedPreferences() {
		
		return context.getSharedPreferences(USER_INFO_KEYS.USER_INFO_PREFERENCES.name(), 0);
		
	}

}
